package com.xiran.srpingboottemplateself.config;

import com.xiran.srpingboottemplateself.filter.JwtLoginProcessingFilter; // 【重要】建议重命名过滤器
import com.xiran.srpingboottemplateself.handler.RestAuthenticationFailureHandler;
import com.xiran.srpingboottemplateself.handler.RestAuthenticationSuccessHandler;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;

/**
 * 配置JWT登录认证流程。
 * 这个配置类将自定义的JWT登录过滤器及其相关的认证提供者集成到Spring Security中。
 * 它替换了默认的用户名密码登录过滤器。
 */


@Component
@RequiredArgsConstructor
public class JwtAuthenticationSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

    private final RestAuthenticationSuccessHandler restAuthenticationSuccessHandler;
    private final RestAuthenticationFailureHandler restAuthenticationFailureHandler;
    private final PasswordEncoder passwordEncoder;
    private final UserDetailsService userDetailsService;
    private final JwtLoginProcessingFilter jwtLoginProcessingFilter; // 【重要】直接注入我们刚创建的那个@Component过滤器

    @Override
    public void configure(HttpSecurity http) throws Exception {

        // 1. 配置认证提供者 (DaoAuthenticationProvider)
        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
        provider.setUserDetailsService(userDetailsService);
        provider.setPasswordEncoder(passwordEncoder);
        http.authenticationProvider(provider);

        // 2. 配置过滤器
        // 因为我们已经在过滤器的类上用了@Component，所以这里直接注入并使用它
        // 只需要为它设置必要的依赖即可
        jwtLoginProcessingFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
        jwtLoginProcessingFilter.setAuthenticationSuccessHandler(restAuthenticationSuccessHandler);
        jwtLoginProcessingFilter.setAuthenticationFailureHandler(restAuthenticationFailureHandler);

        // 3. 将过滤器添加到链中
        http.addFilterBefore(jwtLoginProcessingFilter, UsernamePasswordAuthenticationFilter.class);
    }
}